package grpc_proxy_middleware

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"log"
	"strings"
)

// GRPC metadata 转换
func GRPCMetadataTransferModeMiddleware(service *dao.ServiceDetail) func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
	return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		md, ok := metadata.FromIncomingContext(ss.Context())
		if !ok {
			log.Printf("【GRPC metadata 转换中间件】 failed with error metadata.FromIncomingContext(ss.Context())")
		}
		for _, item := range strings.Split(service.GRPCRule.HeaderTransfor, ",") {
			items := strings.Split(item, " ")
			if len(items) != 3 {
				continue
			}
			if items[0] == "add" || items[0] == "edit" {
				md.Set(items[1], items[2])
			}
			if items[0] == "del" {
				delete(md, items[1])
			}
		}
		md.Delete("app")
		ctx := metadata.NewOutgoingContext(ss.Context(), md)
		if err := handler(srv, &wrappedStream{ss, ctx}); err != nil {
			log.Printf("【GRPC metadata 转换】RPC failed with error %v\n", err)
		}
		return nil
	}
}
